package com.ht.pms.core.controller;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.ht.pms.core.common.exception.ExcelParseException;
import com.ht.pms.core.common.exception.ParamException;
import com.ht.pms.core.dto.Result;
import com.ht.pms.core.dto.ReturnCodeEnum;

@RestControllerAdvice
public class ExceptionControllerAdvice  {


    /**
     * 参数校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException ex) {
//    解析这个异常，然后包装成你想要的数据，就可以返回到前台了
        Result result = new Result();

        result.setCodeDesc(ex.getBindingResult().getFieldError().getField());
        result.setReturnCode(ReturnCodeEnum.ERROR_PARAM.getReturnCode());
        result.setMsg(ex.getBindingResult().getFieldError().getDefaultMessage());

        return result;
    }

    /**
	 * 参数校验异常
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = { ParamException.class })
	@ResponseBody
	public Result throwParamException(ParamException ex) {
		ex.printStackTrace();
		Result result = new Result();

		result.setCodeDesc(ex.getErrorMsg());
		result.setReturnCode(ex.getErrorCode());
		result.setMsg(ex.getErrorMsg());

		return result;
	}
	
	/**
	 * 解析excel自定义异常
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = { ExcelParseException.class })
	@ResponseBody
	public Result throwExcelParseException(ExcelParseException ex) {
		ex.printStackTrace();
		Result result = new Result();

		result.setCodeDesc(ex.getErrorMsg());
		result.setReturnCode(ex.getErrorCode());
		result.setMsg(ex.getErrorMsg());

		return result;
	}

	/**
	 * 系统异常
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	public Result throwException(Exception ex) {
		ex.printStackTrace();
		Result result = new Result();

		result.setCodeDesc(ex.getMessage());
		result.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
		result.setMsg( ReturnCodeEnum.FAIL.getCodeDesc());

		return result;
	}


}
